package main

import (
	"fmt"
	"sort"
)

var (
	closeResChan = false
)

func main() {
	numChan := make(chan int, 2000)
	resChan := make(chan int, 2000)
	finishChan := make(chan bool, 1)
	go writeData(numChan)
	for i := 0; i < 8; i++ {
		go addData(numChan, resChan, finishChan)
	}

	<-finishChan
	res := make([]int, 0, 2000)

	for v := range resChan {
		res = append(res, v)
	}
	sort.Ints(res)
	for i, v := range res {
		fmt.Printf("res[%v] = %v\n", i+1, v)
	}
}

func writeData(numChan chan int) {
	for i := 1; i <= 2000; i++ {
		numChan <- i
		//fmt.Printf("write %v ok \n", i)
	}
	close(numChan)
}

func addData(numChan, resChan chan int, finishChan chan bool) {
	for {
		v, ok := <-numChan
		//fmt.Printf("addData v: %v, ok: %v\n", v, ok)
		if !ok {
			break
		}
		res := 0
		for i := 1; i <= v; i++ {
			res += i
		}
		resChan <- res
	}
	if !closeResChan && len(resChan) >= 2000 {
		closeResChan = true
		finishChan <- true
		close(resChan)
		close(finishChan)
	}
}
